package org.jeecg.modules.controller.xetdoctor;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.modules.xetdoctor.entity.XetDoctor;
import org.jeecg.common.modules.xetdoctor.service.IXetDoctorService;
import org.jeecg.common.modules.xetuser.entity.XetUser;
import org.jeecg.common.modules.xetuser.service.IXetUserService;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.controller.BaseController;
import org.jeecg.modules.data.Common;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/xet_studio")
public class XetDoctorController extends BaseController {
    private String AppId = "wxb1a6ee9de43f2507";
    private String AuthUrl = "https://weixin.api.dyzh120.com/auth?url=";
//    private String RedirectUrl = "https://weixin.dyzh120.com/xet_studio/detail?token=";
    private String goXeStudioUrl = "https://appigc72vmw2720.h5.xiaoeknow.com/mp?pageId=";
    @Resource
    private IWxUserinfoService wxUserinfoService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IXetUserService xetUserService;
    @Resource
    private IXetDoctorService xetDoctorService;

    private String openId = "oRBzQsz5jCpxYSmlliOIesiOYw-0";

    /**
     * 小鹅通跳转到大医智慧客户端后再请求到后端的地址
     * @param pageId
     * @param req
     * @return
     */
    @GetMapping("/detail")
    public Result<?> detail(@RequestParam(name="pageId") String pageId,HttpServletRequest req) {
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            String redirect = Common.operateUrl("studio/"+pageId);
            return Result.error(250,redirect);
        }
        log.info("token：{}",req.getHeader("X-Access-Token"));
        String openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
//        String openId = this.openId;
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            String redirect = Common.operateUrl("studio/"+pageId);
            return Result.error(250,redirect);
        }

        // 用户openId和小鹅通页面pageId绑定关系
        String xetUrl = xetUserService.xetUrl(openId,pageId);
        return Result.ok(xetUrl);
    }

    /**
     * 后台直接授权后跳转到小鹅通工作室
     */
    @GetMapping("/studio")
    public void studio(@RequestParam(name="pageId") String pageId,HttpServletResponse response) throws IOException {
        log.info("重定向后的地址：{}",this.authUrl(pageId));
        response.sendRedirect(this.authUrl(pageId));
    }

    /**
     * 我的医生：小鹅通（公众号菜单跳转）
     */
    @GetMapping("/doctors")
    public Result<?> doctors(HttpServletRequest req){
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            String redirect = Common.operateUrl("xetstudio/doctors");
            return Result.error(250,redirect);
        }
        log.info("token：{}",req.getHeader("X-Access-Token"));
        String openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            String redirect = Common.operateUrl("xetstudio/doctors");
            return Result.error(250,redirect);
        }
//        String openId = this.openId;

        List<XetDoctor> xetDoctors = xetUserService.getDoctorsByOpenid(openId);
        return Result.ok(xetDoctors);
    }

    /**
     * 小鹅通：所有医生列表
     */
    @GetMapping("/doctors/all")
    public Result<?> doctorsAll(){
        List<XetDoctor> xetDoctors = xetDoctorService.getDoctorsAll();
        return Result.ok(xetDoctors);
    }

    /**
     * 小鹅通页面pageId和大医智慧openI的的关系检测
     * @return
     */
    @GetMapping("/relation/check")
    private Result<?> check(String openId,String pageId){
        String str = xetUserService.xetUrl(openId,pageId);
        return Result.ok(str);
    }

    /**
     * 我的医生授权地址
     * @return
     */
    private String authUrl(String pageId){
        log.info("我的医生授权地址");
        return "https://open.weixin.qq.com/connect/oauth2/authorize"
                + "?appid=" + AppId
                + "&redirect_uri=" + AuthUrl + goXeStudioUrl + pageId
                + "&response_type=code&scope=snsapi_userinfo&state=DEFAULT&connect_redirect=1";
    }

    /**
     * 添加数据库压力测试
     * @return
     */
    @GetMapping("/test")
    private Result<Object> test(){
        String openId = this.randNum();
        String pageId = this.randNum();
        redisUtil.setNx("name","哈哈",60);

        SimpleDateFormat sdf  =   new  SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        String date = sdf.format( new  Date());

        Map map = new HashMap();
        map.put("openId",openId);
        map.put("pageId",pageId);
        map.put("xe_page_id",this.randNum());
        map.put("create_time",date);
        map.put("update_time",date);
        redisUtil.hmset(openId,map);
//        boolean res = false;
//        XetUser xetUserCheck = xetUserService.checkOpenIdPage(openId,pageId);
//        if(Objects.nonNull(xetUserCheck)){
//            xetUserCheck.setUpdateTime(new Date());
//            res = xetUserService.updateById(xetUserCheck);
//        }else{
//            // 不存在关系：创建关系
//            XetUser xetUser = new XetUser();
//            xetUser.setOpenid(openId);
//            xetUser.setXePageId(pageId);
//            xetUser.setCreateTime(new Date());
//            xetUser.setUpdateTime(new Date());
//            res = xetUserService.save(xetUser);
//        }
//        if(res){
            return Result.ok(true);
//        }else{
//            return Result.error(String.valueOf(false));
//        }
    }

    public String randNum(){
        int max = 9999999,min=1;
        return  String.valueOf((Math.random()*(max-min)+min));
    }
}
